﻿using System;
using System.Collections.Generic;
using WickedFlame.Core.Shapes;
using WickedFlame.Core.State;

namespace WickedFlame.Core.History
{
    public class ShapeCombineCommand : HistoryCommand
    {
        List<VectorShape> shapes;
        Dictionary<VectorShape, ShapeMemento> states;
        PolygonShape polygon;
        VectorShape polygonReference;

        ShapeMemento polygonOrigMemento;
        ShapeMemento polygonNewMemento;
        ShapeMemento referenceMemento;

        public ShapeCombineCommand(List<VectorShape> shapeList, PolygonShape polygon, VectorShape polygonReference, int layerIndex)
            : base(layerIndex)
        {
            Title = "Shapes combined";
            this.polygon = polygon;
            this.polygonReference = polygonReference;

            shapes = new List<VectorShape>();
            states = new Dictionary<VectorShape, ShapeMemento>();

            foreach (VectorShape shape in shapeList)
            {
                if (shape != polygonReference)
                {
                    //keep reference
                    shapes.Add(shape);
                    if (shape is IStateCapturable)
                        states.Add(shape, ((IStateCapturable)shape).CreateMementoState());
                }
            }

            polygonOrigMemento = ((IStateCapturable)polygon).CreateMementoState();
            if (polygonReference != null)
                referenceMemento = ((IStateCapturable)polygonReference).CreateMementoState();
        }

        /// <summary>
        /// sets the new state of the shapes in the selection list
        /// </summary>
        public void SetNewState()
        {
            polygonNewMemento = ((IStateCapturable)polygon).CreateMementoState();
        }

        public override void Undo(ShapeList list)
        {
            foreach (VectorShape shape in shapes)
                list.Add(shape);

            //if poygon was created of a shape
            if (polygonReference != null)
            {
                list.Remove(polygon);

                ((IStateCapturable)polygonReference).ResetState(referenceMemento);
                list.Add(polygonReference);
            }
            else
            {
                ((IStateCapturable)polygon).ResetState(polygonOrigMemento);
            }
        }

        public override void Redo(ShapeList list)
        {
            foreach (VectorShape shape in shapes)
                list.Remove(shape);

            //if poygon was created of a shape
            if (polygonReference != null)
            {
                ((IStateCapturable)polygon).ResetState(polygonNewMemento);
                list.Add(polygon);

                list.Remove(polygonReference);
            }
            else
            {
                ((IStateCapturable)polygon).ResetState(polygonNewMemento);
            }
        }
    }
}
